package com.ad.dao;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ad.hibernate.Tip;
import com.ad.hibernate.TipView;

public class TipDao extends HibernateDaoSupport implements ITipDao {

	@SuppressWarnings("unchecked")
	@Override
	public Tip findTip(String id) {
		List<Tip> result = this.getHibernateTemplate().find(
				"from Tip where id=" + id);
		if (result == null || result.size() != 1) {
			return null;
		}
		return result.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Tip> findTips() {
		String hql = "from Tip order by createDate desc";
		List<Tip> result = this.getSession().createQuery(hql)
				.setMaxResults(100).list();
		// = this.getHibernateTemplate().find(hql);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Tip> findTipsByCreator(String creator) {
		List<Tip> result = this.getHibernateTemplate().find(
				"from Tip where creator=" + creator);
		if (result == null || result.size() == 0) {
			return null;
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Tip> findTipsByKeyword(String keyword) {
		List<Tip> result = this.getHibernateTemplate().find(
				"from Tip where content like %'" + keyword + "'%");
		if (result == null || result.size() == 0) {
			return null;
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Tip> findTipsByType(String type) {
		List<Tip> result = this.getHibernateTemplate().find(
				"from Tip where tipType=" + type + "'");
		if (result == null || result.size() == 0) {
			return null;
		}
		return result;
	}

	@Override
	public void insert(Tip tip) {
		this.getHibernateTemplate().save(tip);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TipView> findTipViews() {
		String hql = "from TipView order by createDate desc";
		List<TipView> result = this.getSession().createQuery(hql)
				.setMaxResults(100).list();
		// = this.getHibernateTemplate().find(hql);
		return result;
	}

}
